<template>
  <div class="chatroom">
    <header>
      <div class="back" @click="$router.back(-1)">
        <Icon name="arrow-left"></Icon>
      </div>
      <div class="title">{{doctorInfo.nickname}} {{doctorInfo.job}}</div>
      <div>
        <Button size="small" type="danger" v-if="inquiry.status === 1" @click="goEva">结束问诊</Button>
      </div>
    </header>
    <main class="main">
      <!-- 消息内容   渲染 -->
      <div class="chat-content">
        <div
          v-for="(item,index) in chatList"
          :key="index"
          :class="item.fromid === patientInfo._id?'my' : 'doctor'"
        >
          <img
            class="avatar"
            v-lazy="getImageUrl(item.fromid === patientInfo._id ? patientInfo.avatar : doctorInfo.avatar, item.fromid === patientInfo._id ? patientInfo.sex : doctorInfo.sex)"
            alt
          />
          <div class="message">
            <p v-if="item.message.type === 1">{{item.message.content}}</p>
            <img v-if="item.message.type === 2" v-lazy="item.message.content" alt />
          </div>
          <span class="sendtime">{{moment(item.sendtime).locale('zh-cn').format('LTS')}}</span>
        </div>
      </div>
    </main>
    <!-- 消息框 -->
    <footer v-if="inquiry.status === 1">
      <div class="foot-t">
        <Uploader :after-read="uploadImg">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-tupian" />
          </svg>
        </Uploader>
        <svg class="icon" aria-hidden="true" @click="handleUserClick">
          <use xlink:href="#icon-shipin" />
        </svg>
      </div>
      <div class="foot-b">
        <Field v-model="value" placeholder="请输入内容" />
        <Button size="small" round @click="onSend">发送</Button>
      </div>
    </footer>
    <!-- 视频通话   点击视频的时候出现 -->
    <div id="video-div" v-show="videoShow">
      <video id="remote-video" autoplay :class="videoChange ? 'big-video' : 'small-video'" @click="change"/>
      <video
        id="local-video"
        :class="videoChange ? 'small-video' : 'big-video'"
        @click="change"
        autoplay
      ></video>
      <Button type="danger" @click="stopTrack">关闭</Button>
    </div>
  </div>
</template>

<script>
import { Icon, Button, Field, Dialog, Uploader } from 'vant'
import BScroll from 'better-scroll'
import moment from 'moment'
import { getDoctorInfo, getSelf, inquiryMsg, getChatHistory, getImageUrl, finishInquiry, sendChat } from '../../../api/api/index'
import socket, { startVideoTalk, stopVideoTalk, onFallEvent } from '@/api/api/websocket';
import { mapState } from 'vuex'
export default {

  components: {
    Icon,
    Button,
    Field,
    Uploader
  },
 
  data() {
    return {
      doctorInfo: {},       //医生信息
      inquiry: {},  
      patientInfo: {},      //患者信息
      chatList: [],         //聊天数据
      value: '',
      bscroll: null,
      videoShow: false,         //通话框显示
      videoChange: true         //点击的时候  视频框 变大
    }
  },
  mounted() {
    
    //上拉加载
    this.bscroll = new BScroll('.main')
    this.init()
    onFallEvent.onClose = (msg) => {
      this.videoShow = false;
    }
    socket.on('inquiry', (msg) => {
      msg = JSON.parse(msg);
      console.log(msg)
      const { fromid, toid, message, inquiryid } = msg;
      if (toid === this.inquiry.patientid) {
        // 发送给自己的数据
        this.chatList.push({
          inquiryid,
          fromid,
          toid,
          message
        });
        this.$nextTick(() => {
          this.bscroll.refresh()
          setTimeout(() => {
            this.bscroll.scrollTo(0, this.bscroll.maxScrollY)
          }, 200)
        })
      }
    })
  },
  methods: {
    moment,
    getImageUrl,
    // 点击通话开始
    handleUserClick() {
      this.videoShow = true;
      this.$nextTick(() => {
        // 调用一波通话函数
        startVideoTalk(this.inquiry.doctorid);
      });
    },
    // 视频框变小
    stopTrack() {
      this.videoShow = false
      stopVideoTalk();
    },
    //视频框大小
    change() {
      this.videoChange = !this.videoChange
    },
    async init() {
      // 获取聊天室信息
      const inquiry = await inquiryMsg(this.$route.params.id)
      if (inquiry.code === 200) {
        this.inquiry = inquiry.data[0]
        console.log('inquiry----', this.inquiry)
      }
      // 获取医生信息
      const doctorInfo = await getDoctorInfo(this.$route.query.doctor_id || this.inquiry.doctorid)
      if (doctorInfo.code === 200) {
        this.doctorInfo = doctorInfo.data[0]
        console.log('doctorInfo-----', this.doctorInfo)
      }
      // 获取患者信息
      const patientInfo = await getSelf()
      if (patientInfo.code === 200) {
        this.patientInfo = patientInfo.data[0]
        console.log('patientInfo-----', this.patientInfo)
      }
      // 获取聊天列表信息
      const ChatHistory = await getChatHistory(this.inquiry._id)
      console.log(ChatHistory)
      if (ChatHistory.code === 200) {
        this.chatList = ChatHistory.data
        console.log('连天使', this.chatList)
        this.$nextTick(() => {
          this.bscroll.refresh()
          setTimeout(() => {
            this.bscroll.scrollTo(0, this.bscroll.maxScrollY)
          }, 400)
        })
      }
    },
    // 关闭 问诊
    goEva() {
      Dialog.confirm({
        title: '提示',
        message: '是否确认结束问诊'
      }).then(() => {
        // 结束问诊，修改当前问诊状态
        finishInquiry(this.inquiry._id, { status: 2 }).then(res => {
          if (res.code === 200) {
            this.$store.commit('patientStore/flag', false);
            this.$router.replace({
              path: '/home/case',
              query: {
                doctor: this.doctorInfo,
                inquiryid: this.inquiry._id
              }
            })
          }
        })
      })
    },
    //点击发送一波
    onSend() {
      //判断是否输入为空
      if (this.value.trim().length === 0) {
        this.$toast.fail('请输入内容');
        return
      }
      const message = {
        type: 1,
        content: this.value
      }
      this.sendMessage(message);
      this.value = '';
    },
    sendMessage(message) {
      console.log(77)
      //传送  患者id  医生id  信息
      const data = {
        inquiryid: this.inquiry._id,
        fromid: this.inquiry.patientid,
        toid: this.inquiry.doctorid,
        message: message
      }
      //数据发送给后台
      sendChat(data).then(res => {
        console.log(88)
        if (res.code === 200) {
          console.log(res)
          this.chatList.push(res.data);
          this.$nextTick(() => {
            this.bscroll.refresh()
            setTimeout(() => {
              this.bscroll.scrollTo(0, this.bscroll.maxScrollY)
            }, 200)
          })
        }
      })
    },
    uploadImg(file) {
      if (!file.content) return;
      const message = {
        type: 2,
        content: file.content
      }
      this.sendMessage(message);
    }
  }
}
</script>

<style lang="scss">
@import "@/assets/scss/index.scss";
// .chatroom .foot-t{
//   display: flex;
//   svg,.van-uploader{
//     width: 100%;
//     height: 100%;
//   }
// }
.chatroom {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  header {
    height: 0.5rem;
    display: flex;
    padding: 0 0.3rem;
    box-sizing: border-box;
    justify-content: space-between;
    align-items: center;
    border-bottom: 0.01rem solid #f3f3f3;
    .back {
      i {
        font-size: 12px;
      }
    }
    .title {
      font-size: 12px;
    }
  }
  main {
    flex: 1;
    overflow: auto;
    background: #f3f3f3;
    width: 100%;
    .chat-content {
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      padding: 0.1rem;
    }
    .my {
      height: auto;
      margin-top: 0.14rem;
      .avatar,
      .message,
      .sendtime {
        float: right;
      }
    }
    .doctor {
      height: auto;
      margin-top: 0.14rem;
      .avatar,
      .message,
      .sendtime {
        float: left;
      }
    }
    .avatar {
      width: 0.4rem;
      height: 0.4rem;
      border-radius: 50%;
    }
    .message {
      max-width: 1.8rem;
      margin: 0 0.1rem;
      padding: 0.08rem;
      background: #fff;
      border-radius: 0.1rem;
      height: auto;
      p {
        line-height: 0.2rem;
      }
      img {
        width: 100%;
      }
    }
    span.sendtime {
      font-size: 0.12rem;
      margin-top: 0.1rem;
    }
  }
  footer {
    height: auto;
    .foot-t {
      height: 0.34rem;
      padding-left: 0.2rem;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .icon {
        width: 0.25rem;
        height: 100%;
        font-size: 12px;
        margin-right: 0.1rem;
      }
      >svg.icon{
          width: 0.3rem;
      }
    }
    .foot-b {
      height: 0.5rem;
      box-sizing: border-box;
      padding: 0 0.2rem;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .van-cell {
        padding: 0;
        height: 100%;
        .van-field__body {
          height: 100%;
        }
      }
      .van-button {
        width: 0.6rem;
        background: #20a8dd;
        color: #fff;
      }
    }
  }
}
#video-div {
  position: fixed;
  width: 100%;
  height: 1.6rem;
  right: 0;
  bottom: 0;
  background-color: #eeeeee;
  .small-video {
    width: 40%;
    height: 50%;
    position: absolute;
    bottom: 0;
    right: 0;
    z-index:2
  }
  .big-video{
    position: absolute;
    left:0;
    top:0;
    width: 100%;
    height: 100%;
    z-index:1
  }
  button{
    position: absolute;
    top:0.06rem;
    right:0.06rem;
    z-index:2
  }
}
</style>
